package org.tinygroup.fulltextweb;

import java.util.ArrayList;
import java.util.List;

import org.tinygroup.fulltext.FullText;
import org.tinygroup.fulltext.FullTextHelper;
import org.tinygroup.fulltext.Pager;
import org.tinygroup.fulltext.document.Document;
import org.tinygroup.fulltext.document.HighlightDocument;
import org.tinygroup.logger.LogLevel;
import org.tinygroup.logger.Logger;
import org.tinygroup.logger.LoggerFactory;
import org.tinygroup.weblayer.WebContext;
import org.tinygroup.weblayer.mvc.WebContextAware;
import org.tinygroup.weblayer.mvc.annotation.Controller;
import org.tinygroup.weblayer.mvc.annotation.RequestMapping;
import org.tinygroup.weblayer.mvc.annotation.View;

/**
 * 查询操作
 * @author yancheng11334
 *
 */
@Controller
public class SearchAction implements WebContextAware {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(SearchAction.class);
	
	private WebContext webContext;
	
	
	public SearchAction(){
		super();
	}
	
	public void setContext(WebContext webContext) {
		this.webContext = webContext;
	}

	@RequestMapping("/search.do")
	@View(value = "/search.page")
	public void searchMethod() {
		String searchCondition = (String) webContext.get("searchCondition");
		String start = (String) webContext.get("start");
		String limit = (String) webContext.get("limit");
		
		FullText fullText = FullTextHelper.getFullText();
		
		LOGGER.logMessage(LogLevel.INFO, "全文检索开始...");
		Pager<Document> result = fullText.search(searchCondition, Integer.parseInt(start), Integer.parseInt(limit));
		LOGGER.logMessage(LogLevel.INFO, "全文检索结束!");
		
		webContext.put("docs", result.getTotalCount());
		webContext.put("pages", result.getTotalPages());
		webContext.put("page", result.getCurrentPage());
		webContext.put("newResult", createSearchDocuments(result.getRecords()));
		
	}
	
	private List<HighlightDocument> createSearchDocuments(List<Document> list){
		List<HighlightDocument> newResult = new ArrayList<HighlightDocument>();
		for(Document doc : list){
			HighlightDocument document = new HighlightDocument(doc,"<font color='red'>","</font>");
			newResult.add(document);
		}
		return newResult;
	}
}
